# WhatsApp平台 Windows服务器部署脚本
# 使用管理员权限运行PowerShell执行

param(
    [Parameter(Mandatory=$true)]
    [string]$Domain
)

Write-Host "🚀 WhatsApp平台 Windows服务器部署脚本" -ForegroundColor Green
Write-Host "========================================" -ForegroundColor Green

Write-Host "🌐 部署域名: $Domain" -ForegroundColor Cyan
Write-Host "📁 部署目录: C:\inetpub\whatsapp-platform" -ForegroundColor Cyan

# 检查管理员权限
if (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
    Write-Host "❌ 请以管理员身份运行PowerShell" -ForegroundColor Red
    exit 1
}

# 确认部署
$response = Read-Host "⚠️  即将开始部署，此过程可能需要30-45分钟。确认继续吗？(y/N)"
if ($response -notmatch "^[Yy]$") {
    Write-Host "部署已取消" -ForegroundColor Yellow
    exit 0
}

$startTime = Get-Date

try {
    # 步骤1：安装必要的Windows功能
    Write-Host "`n📦 步骤1/9: 启用Windows功能..." -ForegroundColor Yellow
    
    # 启用IIS
    Enable-WindowsOptionalFeature -Online -FeatureName IIS-WebServerRole, IIS-WebServer, IIS-CommonHttpFeatures, IIS-HttpErrors, IIS-HttpLogging, IIS-RequestFiltering, IIS-StaticContent, IIS-DefaultDocument, IIS-DirectoryBrowsing -All
    
    # 启用IIS应用程序开发功能
    Enable-WindowsOptionalFeature -Online -FeatureName IIS-WebSockets, IIS-ApplicationInit, IIS-ASPNET45 -All
    
    Write-Host "✅ Windows功能启用完成" -ForegroundColor Green

    # 步骤2：安装Chocolatey包管理器
    Write-Host "`n📦 步骤2/9: 安装Chocolatey包管理器..." -ForegroundColor Yellow
    
    if (!(Get-Command choco -ErrorAction SilentlyContinue)) {
        Set-ExecutionPolicy Bypass -Scope Process -Force
        [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072
        iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1'))
        Write-Host "✅ Chocolatey安装完成" -ForegroundColor Green
    } else {
        Write-Host "✅ Chocolatey已存在" -ForegroundColor Green
    }

    # 步骤3：安装Node.js
    Write-Host "`n📦 步骤3/9: 安装Node.js..." -ForegroundColor Yellow
    choco install nodejs -y --version=18.19.0
    
    # 刷新环境变量
    $env:Path = [System.Environment]::GetEnvironmentVariable("Path","Machine") + ";" + [System.Environment]::GetEnvironmentVariable("Path","User")
    
    Write-Host "✅ Node.js安装完成" -ForegroundColor Green

    # 步骤4：安装Chrome
    Write-Host "`n📦 步骤4/9: 安装Google Chrome..." -ForegroundColor Yellow
    choco install googlechrome -y
    Write-Host "✅ Chrome安装完成" -ForegroundColor Green

    # 步骤5：安装PM2
    Write-Host "`n📦 步骤5/9: 安装PM2..." -ForegroundColor Yellow
    npm install -g pm2
    npm install -g pm2-windows-startup
    pm2-startup install
    Write-Host "✅ PM2安装完成" -ForegroundColor Green

    # 步骤6：安装URL Rewrite模块
    Write-Host "`n📦 步骤6/9: 安装IIS URL Rewrite..." -ForegroundColor Yellow
    choco install urlrewrite -y
    Write-Host "✅ URL Rewrite安装完成" -ForegroundColor Green

    # 步骤7：创建项目目录并复制文件
    Write-Host "`n📁 步骤7/9: 设置项目文件..." -ForegroundColor Yellow
    
    $projectDir = "C:\inetpub\whatsapp-platform"
    if (Test-Path $projectDir) {
        Remove-Item $projectDir -Recurse -Force
    }
    New-Item -ItemType Directory -Path $projectDir -Force
    
    # 复制项目文件
    Copy-Item -Path ".\*" -Destination $projectDir -Recurse -Force
    Set-Location $projectDir
    
    Write-Host "✅ 项目文件设置完成" -ForegroundColor Green

    # 步骤8：配置环境变量
    Write-Host "`n⚙️  步骤8/9: 配置环境变量..." -ForegroundColor Yellow
    
    Set-Location "$projectDir\backend"
    
    if (!(Test-Path ".env")) {
        Copy-Item ".env-example" ".env"
        
        # 生成安全密钥
        $jwtSecret = -join ((1..128) | ForEach {[char]((48..57)+(65..90)+(97..122) | Get-Random)})
        $encryptionKey = -join ((1..64) | ForEach {[char]((48..57)+(65..90)+(97..122) | Get-Random)})
        
        # 更新.env文件
        (Get-Content ".env") | 
            ForEach-Object { $_ -replace "NODE_ENV=development", "NODE_ENV=production" } |
            ForEach-Object { $_ -replace "PROXY_ENABLED=true", "PROXY_ENABLED=false" } |
            ForEach-Object { $_ -replace "LOG_LEVEL=debug", "LOG_LEVEL=info" } |
            Set-Content ".env"
        
        # 添加生成的密钥
        Add-Content ".env" "`n# 自动生成的安全密钥"
        Add-Content ".env" "JWT_SECRET=$jwtSecret"
        Add-Content ".env" "ENCRYPTION_KEY=$encryptionKey"
        Add-Content ".env" "ALLOWED_ORIGINS=https://$Domain"
        Add-Content ".env" "WHATSAPP_DATA_PATH=.\whatsapp-session"
        
        Write-Host "⚠️  重要提醒：" -ForegroundColor Red
        Write-Host "   请编辑 $projectDir\backend\.env 文件" -ForegroundColor Yellow
        Write-Host "   设置正确的 MONGO_URI 连接字符串" -ForegroundColor Yellow
        Write-Host "   按任意键继续..." -ForegroundColor Yellow
        $null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
    }
    
    Write-Host "✅ 环境变量配置完成" -ForegroundColor Green

    # 步骤9：安装依赖和构建
    Write-Host "`n📦 步骤9/9: 安装依赖和构建..." -ForegroundColor Yellow
    
    Set-Location $projectDir
    
    # 安装后端依赖
    Set-Location "$projectDir\backend"
    npm install
    
    # 安装前端依赖和构建
    Set-Location "$projectDir\frontend"
    npm install
    npm run build
    
    # 创建必要目录
    Set-Location "$projectDir\backend"
    New-Item -ItemType Directory -Path "logs" -Force
    New-Item -ItemType Directory -Path "uploads\media" -Force
    New-Item -ItemType Directory -Path "uploads\temp" -Force
    New-Item -ItemType Directory -Path "whatsapp-session" -Force
    
    Write-Host "✅ 依赖安装和构建完成" -ForegroundColor Green

    # 创建PM2配置文件
    $pm2Config = @"
module.exports = {
  apps: [{
    name: 'whatsapp-platform',
    script: './backend/src/index.js',
    cwd: '$($projectDir.Replace('\', '/'))',
    instances: 1,
    exec_mode: 'fork',
    env: {
      NODE_ENV: 'production',
      PORT: 3001
    },
    log_file: './backend/logs/combined.log',
    out_file: './backend/logs/out.log',
    error_file: './backend/logs/error.log',
    log_date_format: 'YYYY-MM-DD HH:mm Z',
    merge_logs: true,
    max_memory_restart: '1G',
    restart_delay: 5000,
    max_restarts: 10,
    min_uptime: '10s'
  }]
};
"@
    
    Set-Content -Path "$projectDir\ecosystem.config.js" -Value $pm2Config

    # 启动PM2应用
    Set-Location $projectDir
    pm2 start ecosystem.config.js
    pm2 save

    # 计算部署时间
    $endTime = Get-Date
    $duration = $endTime - $startTime
    $minutes = [math]::Floor($duration.TotalMinutes)
    $seconds = $duration.Seconds

    Write-Host "`n🎉 基础部署完成！" -ForegroundColor Green
    Write-Host "===================" -ForegroundColor Green
    Write-Host "⏱️  总用时: $minutes 分 $seconds 秒" -ForegroundColor Cyan
    Write-Host "`n📋 部署信息:" -ForegroundColor Cyan
    Write-Host "   域名: $Domain" -ForegroundColor White
    Write-Host "   项目目录: $projectDir" -ForegroundColor White
    Write-Host "   后端端口: 3001" -ForegroundColor White
    
    Write-Host "`n📝 下一步操作:" -ForegroundColor Yellow
    Write-Host "1. 配置IIS:" -ForegroundColor White
    Write-Host "   运行: .\windows-setup-iis.ps1 $Domain" -ForegroundColor Gray
    Write-Host "`n2. 检查应用状态:" -ForegroundColor White
    Write-Host "   pm2 status" -ForegroundColor Gray
    Write-Host "   pm2 logs whatsapp-platform" -ForegroundColor Gray
    Write-Host "`n3. 配置MongoDB连接:" -ForegroundColor White
    Write-Host "   编辑 $projectDir\backend\.env" -ForegroundColor Gray
    Write-Host "   然后重启: pm2 restart whatsapp-platform" -ForegroundColor Gray

} catch {
    Write-Host "`n❌ 部署过程中出现错误: $($_.Exception.Message)" -ForegroundColor Red
    exit 1
} 